<template>
  <div class="stock">
    <van-cell is-link icon="./imgs/stock_icon.png" size="large">
      <template #title>
        <h5>股票榜单</h5>
      </template>
    </van-cell>

    <!-- 股票榜单 -->
    <van-tabs v-model="active">
      <van-tab :title="markets[i]" v-for="(item, i) in stocks" :key="i">
        <van-cell-group inset>
          <van-cell>
            <template>
              <div
                class="stock_item"
                v-for="(stock, index) in stocks[i]"
                :key="index"
              >
                <span class="num">{{ index + 1 }}</span>
                <span class="name">{{ stock.name }}</span>
                <span class="arrow" :class="stock.percent >= 0 ? 'up' : 'down'">
                  <van-icon name="down" />
                </span>
                <span class="value">{{ stock.value }}</span>
              </div>
            </template>
          </van-cell>
        </van-cell-group>
      </van-tab>
    </van-tabs>
  </div>
</template>

<script>
import * as api from "@/api/index";
export default {
  data() {
    return {
      active: 0,
      markets: ["全球", "沪深", "港股", "美股"],
      stocks: [],
    };
  },
  mounted() {
    let num = 0;
    this.markets.forEach(async (item, i) => {
      let result = await api.getStocks({ type: i });
      // 向响应式对象中添加一个 property，并确保这个新 property 同样是响应式的，且触发视图更新。
      this.$set(this.stocks, i, result.data.items);
      //   console.log(this.stocks);
      //修改数组的时候，push、pop、shift、unshift、splice、sort、reverse都会触发页面的更新
      //   this.stocks.push(result.data.items);
      //   this.stocks[i]是不会触发页面更新
      //   this.stocks[i] = result.data.items;

      //num++;
      //   if (num == 4) {
      //     console.log(this);
      //     // 解决不更新，可以在数据所有获取回来后，统一重新创建数组，并且将之前的数组内容解构进去
      //     // this.stocks = [...this.stocks];
      //     // 调用Vue框架自带的强制更新的方法，进行页面更新
      //     // this.$forceUpdate();
      //   }
    });
  },
};
</script>

<style lang="less" scoped>
.stock {
  h5 {
    font-size: 0.4rem;
    margin: 0;
    color: #666;
  }
  .van-icon img {
    width: 25px;
    height: 25px;
  }

  .arrow.up {
    transform-origin: center;
    transform: rotate(180deg);
    color: red;
  }
  .arrow.down {
    color: green;
  }

  .stock_item {
    display: flex;
    height: 40px;
    .num {
      flex: 1;
    }
    .name {
      flex: 7;
    }
    .arrow {
      flex: 1;
      display: flex;
      justify-content: center;
      align-items: center;
    }
    .value {
      flex: 2;
      display: flex;
      justify-content: flex-end;
      align-items: center;
    }
  }

  ::v-deep .van-tabs__line {
    background-color: #1989fa;
  }
}
</style>
